import flash.external.ExternalInterface;

import gugga.events.EventDispatcher;

[Event("changed")]
class gugga.browser.BrowserHistory extends EventDispatcher
{
	private static var mInstance : BrowserHistory = null;
	public static function get Instance() : BrowserHistory
	{
		if(mInstance == null)
		{
			mInstance = new BrowserHistory();
		}
		return mInstance;
	}
	
	private function BrowserHistory()
	{
		super();
		
		ExternalInterface.addCallback("changeHistory", this, this.changeHistory);	
	}
	
	public static function get available() : Boolean
	{
		return ExternalInterface.available;
	}
	
	public function addHistory(aRecord : Object) : Void
	{
		ExternalInterface.call("addHistory", formatHisoryRecord(aRecord));
	}
	
	private function changeHistory(aRecord : String) : Void
	{
		dispatchEvent({type : "changed", target : this, record : parseHistoryRecord(aRecord)});
	}
	
	private function formatHisoryRecord(aRecordObject : Object) : String
	{
		var result : String = "";
		for (var key : String in aRecordObject)
		{
			if(result != "")
			{
				result += "&";
			}
			result += (key + "=" + aRecordObject[key]);
		}
		return result;	
	}
	
	private function parseHistoryRecord(aRecord : String) : Object
	{
		var result : Object = new Object();
		var pairs : Array = aRecord.split("&");
		for (var i : Number = 0; i < pairs.length; i++)
		{
			var pair : Array = pairs[i].split("=");
			result[unescape(pair[0])] = unescape(pair[1]);
		}
		return result;
	}
}